from flask import Flask, jsonify, request
import uuid
import json

app = Flask(__name__)

# 加载 JSON 数据库文件
def load_database(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)

# 模拟存储干预方案的数据库
intervention_plans = load_database('./DBFiles/intervention_plans_db.json')
# 模拟存储转人工请求的数据库
transfer_requests = load_database('./DBFiles/transfer_requests_db.json')


@app.route('/assess_and_intervene', methods=['POST'])
def assess_and_intervene():
    # 因为没有实际的数据，接下来使用模拟数据
    # data = request.get_json()
    # user_profile = data.get('user_profile')
    # emotion_level = data.get('emotion_level')
    user_profile = {
        "patient_name": "小明",
        "patient_age": 30,
        "patient_gender": "男"
    }
    emotion_level = '中度'

    if emotion_level in ['重度', '中度']:
        user_id = user_profile.get('user_id')
        reason = "情绪问题达到中重度，需人工干预"
        transfer_id = str(uuid.uuid4())
        transfer_requests[transfer_id] = {
            "user_id": user_id,
            "reason": reason,
            "status": "processing"
        }
        return jsonify({"transfer_info": transfer_requests[transfer_id], "message": "已为您转接人工服务，请稍候"})

    elif emotion_level in ['轻度', '亚健康']:
        intervention_plan_id = str(uuid.uuid4())
        problem_type = classify_problem(user_profile)
        plan_details = generate_intervention_plan(problem_type)
        intervention_plans[intervention_plan_id] = plan_details
        return jsonify({"intervention_plan_id": intervention_plan_id, "message": "自助干预方案已生成"})

    else:
        return jsonify({"errCode": "invalid_emotion_level", "message": "无效的情绪程度标识"}), 200


def classify_problem(user_profile):
    # 简单模拟问题分类
    if "工作" in user_profile.get('description', ""):
        return "工作压力"
    elif "人际关系" in user_profile.get('description', ""):
        return "人际关系问题"
    else:
        return "其他"


def generate_intervention_plan(problem_type):
    # 简单模拟生成干预方案
    if problem_type == "工作压力":
        return "建议您合理安排工作时间，每天抽出1小时进行放松活动，如听音乐、散步等。"
    elif problem_type == "人际关系问题":
        return "建议您主动与他人沟通，每周参加一次社交活动，改善人际关系。"
    else:
        return "请保持良好的生活习惯，适当运动，保证充足睡眠。"


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5003)


